#include "EventHandler.h"
#include <iostream>


bool EventHandler::m_event_state[EH_NUMOPTS][EH_NUMTIMES];
bool EventHandler::m_running;
std::map<SDLKey,EventState> EventHandler::m_sdlk2eh;

void EventHandler::init(){
  m_running = true;
  m_sdlk2eh[SDLK_w] = EH_W;
  m_sdlk2eh[SDLK_a] = EH_A;
  m_sdlk2eh[SDLK_s] = EH_S;
  m_sdlk2eh[SDLK_d] = EH_D;
  m_sdlk2eh[SDLK_UP] = EH_UP;
  m_sdlk2eh[SDLK_DOWN] = EH_DOWN;
  m_sdlk2eh[SDLK_LEFT] = EH_LEFT;
  m_sdlk2eh[SDLK_RIGHT] = EH_RIGHT;
  m_sdlk2eh[SDLK_o] = EH_O;
  m_sdlk2eh[SDLK_p] = EH_P;
}


bool EventHandler::getState(EventState estate, EventTime etime){
  return m_event_state[estate][etime];
}

bool EventHandler::isRunning(){
  return m_running;
}

void EventHandler::pollEvents(){
  setHistory();
  SDL_Event Event;
  while(SDL_PollEvent(&Event)) {
    onEvent(&Event);
  }
}

void EventHandler::setHistory(){
  for(int et = EH_NUMTIMES-1; et > EH_CUR; et--){
    for(int es = 0; es < EH_NUMOPTS; es++){
      m_event_state[es][et] = m_event_state[es][et-1];
    }
  }
}

void EventHandler::onEvent(SDL_Event* Event){
  bool evalue = false;
  switch(Event->type){
  case SDL_KEYDOWN:
    evalue = true;
  case SDL_KEYUP:
    m_event_state[m_sdlk2eh[Event->key.keysym.sym]][EH_CUR] = evalue;
    break;
  case SDL_QUIT:
    m_running = false;
    break;
  default:
    break;
  }
}

